﻿using System;
using System.Collections.Generic;
using MoreExtentions;

namespace MoreExtentions
{
    public class KeyEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>
    {
        private readonly Func<TSource, TKey> projection;
        private readonly IEqualityComparer<TKey> comparer;

        public KeyEqualityComparer(Func<TSource, TKey> projection)
            : this(projection, null)
        {
        }

        public KeyEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer)
        {
            projection.ThrowIfNull("projection");
            this.comparer = comparer ?? EqualityComparer<TKey>.Default;
            this.projection = projection;
        }

        public bool Equals(TSource x, TSource y)
        {
            if (x == null && y == null)
                return true;

            if (x == null || y == null)
                return false;

            return comparer.Equals(projection(x), projection(y));
        }

        public int GetHashCode(TSource obj)
        {
            if (obj == null)
                throw new ArgumentNullException("obj");
            return comparer.GetHashCode(projection(obj));
        }
    }
}